package com.macrosolution.exdebito

import grails.plugin.springsecurity.annotation.Secured;
import grails.transaction.Transactional;
import grails.converters.JSON

@Secured(['ROLE_ADMIN','ROLE_AMM','ROLE_CC','ROLE_C'])
class RoleController extends grails.plugin.springsecurity.ui.RoleController {
	def springSecurityService
	
	def save(){
		Role role;
		if(params.id){
			role=Role.get(params.getLong('id'));
			role.properties=params
		}else{
			role= new Role(params)
		}
		role.save(flush:true)
		redirect action:'show' 
	}
	
	def get_update_role(){
		Role role= Role.get(params.getLong('id'));
		render view:'create',model:[role:role]
	}
	
	def search(){
		
	}
	
	def create(){
	
	}
	
	def show(){
		
	}
	@Transactional
	def delete(){
		def role=Role.get(params.getLong('id'));
		UserRole userRole = UserRole.findByRole(role);
		if(userRole){
			role.errors.rejectValue("priority", "xxx",
				['yyy'] as Object[],
				"Questo ruolo è legato ad un utente attivo e non può essere cancellato!")
		}else{
			role.delete()
		}
		render view:'show',model:[role:role]
	}
	def get_roles(){
		User secUser =springSecurityService.currentUser
		int privilege=100;
		secUser.getAuthorities().each {Role role->
			if(role.priority<privilege){
				privilege=role.priority;
			}
		}
		List roles = Role.findAllByPriorityGreaterThan(privilege,[sort: "priority", order: "asc"]);
		render 	roles as JSON
	}
	
	def get_add_role(){
		render view:'create'
	}
		
}
